import { defineStore } from 'pinia'

interface CacheItem<T> {
  data: T
  timestamp: number
  expireTime?: number
}

interface CacheState {
  items: Record<string, CacheItem<any>>
}

export const useCacheStore = defineStore('cache', {
  state: (): CacheState => ({
    items: {},
  }),

  getters: {
    // 获取缓存项
    getItem: (state) => {
      return <T>(key: string): T | null => {
        const item = state.items[key]
        if (!item)
          return null

        // 检查是否过期
        if (item.expireTime && Date.now() > item.expireTime) {
          delete state.items[key]
          return null
        }

        return item.data as T
      }
    },
  },

  actions: {
    // 设置缓存
    setItem<T>(key: string, data: T, expireTime?: number) {
      this.items[key] = {
        data,
        timestamp: Date.now(),
        expireTime: expireTime ? Date.now() + expireTime : undefined,
      }
    },

    // 移除缓存
    removeItem(key: string) {
      delete this.items[key]
    },

    // 清空缓存
    clear() {
      this.items = {}
    },

    // 清理过期缓存
    cleanup() {
      const now = Date.now()
      Object.keys(this.items).forEach((key) => {
        const item = this.items[key]
        if (item.expireTime && now > item.expireTime) {
          delete this.items[key]
        }
      })
    },
  },

  persist: {
    key: 'ECHO-CACHE',
    storage: {
      getItem: (key: string) => {
        return uni.getStorageSync(key)
      },
      setItem: (key: string, value: any) => {
        uni.setStorageSync(key, value)
      },
    },
  },
})
